package com.example.callcenter.util;

import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Component
public class ExcelExportUtil {

    /**
     * 导出Excel（大数据量支持）
     */
    public void exportExcel(HttpServletResponse response, String fileName,
                            String[] titles, List<Map<String, Object>> data) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" +
                URLEncoder.encode(fileName, "UTF-8") + ".xlsx");

        // 使用SXSSFWorkbook处理大数据量
        try (SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
             OutputStream out = response.getOutputStream()) {

            Sheet sheet = workbook.createSheet("数据导出");
            Row titleRow = sheet.createRow(0);

            // 创建标题行
            for (int i = 0; i < titles.length; i++) {
                Cell cell = titleRow.createCell(i);
                cell.setCellValue(titles[i]);
                // 设置标题样式
                CellStyle style = workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
            }

            // 填充数据
            for (int i = 0; i < data.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Map<String, Object> rowData = data.get(i);
                for (int j = 0; j < titles.length; j++) {
                    Cell cell = row.createCell(j);
                    Object value = rowData.get(titles[j]);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }

            // 写入输出流
            workbook.write(out);
            out.flush();
        }
    }
}